// pages/login/login.js
import {
  request
} from '../../utils/asyncWX'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    loading: false,
  },
  onLoad(e) {
    if (e) {
      wx.showToast({
        title: e.msg,
        icon: 'none'
      })
    }
  },
  handleLogin() {
    const _this = this
    _this.setData({
      loading: true
    })
    wx.getUserProfile({
      desc: '用于完善用户信息',
      success: async (res) => {
        wx.setStorageSync('userInfo', res.userInfo)
        try {
          const {
            code
          } = await wx.login({
            timeout: 60000
          })
          if (code) {
            const data = {
              code,
              nickname: res.userInfo.nickName,
              avatar: res.userInfo.avatarUrl
            }
            const res1 = await request({
              url: '/api/wxLogin',
              data,
              method: 'post'
            })
            if (res1.data.code == 200) {
              wx.setStorageSync('token', res1.data.data.token)
              wx.showToast({
                title: res1.data.msg,
                icon: 'none',
              })
              // 登录成功跳转
              setTimeout(() => {
                wx.switchTab({
                  url: '/pages/index/index',
                })
              }, 400)
            }
            if (res1.code == 201) {
              wx.showToast({
                title: res1.msg,
                icon: 'none',
              })
            }
          }
        } catch (err) {
          console.log(err);
          wx.showToast({
            title: '登录出错',
            icon: 'none',
          })
        }
      },
      complete: () => {
        _this.setData({
          loading: false
        })
      }
    })
  }
})